/** QC passed
 * 02-Apr-2011 Created
 * 02-Apr-2011 Deal with potential JSON trojans/spoofs on indempotent request - log in as A delete/edits B's data
 */
package com.munoor.dalai.server.api;

import javax.persistence.EntityManager;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

import com.munoor.dalai.server.model.EMFService;
import com.munoor.dalai.server.model.Filter;
import com.munoor.dalai.server.model.wrappers.WrappedFilter;
import com.sun.jersey.api.NotFoundException;

/**
 * @author Osho Ilamah
 * @since version 1.0 (April 2011)
 */
public class FilterResource {
	@Context
	UriInfo uriInfo;
	@Context
	Request request;
	Long id;

	public FilterResource(UriInfo uriInfo, Request request, Long id) {
		this.uriInfo = uriInfo;
		this.request = request;
		this.id = id;
	}

	@GET
	@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
	public WrappedFilter readFilter() {
		EntityManager em = EMFService.get().createEntityManager();
		try {
			return new WrappedFilter(((Filter) em.createNamedQuery("Filters.findByFilterId").setParameter("filterId", id).getSingleResult()));
		} catch (Exception e) {
			throw new NotFoundException("Not Found");
		} finally {
			em.close();
		}
	}

	@PUT
	@Consumes(MediaType.APPLICATION_JSON)
	public Response updateFilter(WrappedFilter postData) {
		EntityManager em = EMFService.get().createEntityManager();
		Filter filter = null;
		try {
			filter = postData.unmarshall();
		} catch (Exception e) {
			em.close();
			return Response.serverError().build();
		}
		// check this idempotent request data is permitted for the authorisation scope
		// i.e. (JSON data userID matches path userID which will already have been authorized)
		if (uriInfo.getPath().indexOf("users/" + filter.getUserId() + "/") == -1) {
			em.close();
			throw new NotFoundException("Not Found");
		}
		em.merge(filter);
		em.close();
		return Response.noContent().build();
	}

	@DELETE
	public Response deleteFilter() {
		EntityManager em = EMFService.get().createEntityManager();
		Filter filter = null;
		try {
			filter = (Filter) em.createNamedQuery("Filters.findByFilterId").setParameter("filterId", id).getSingleResult();
		} catch (Exception e) {
			em.close();
			throw new NotFoundException("Not Found");
		}
		if (uriInfo.getPath().indexOf("users/" + filter.getUserId() + "/") == -1) {
			em.close();
			throw new NotFoundException("Not Found");
		}
		em.remove(filter);
		em.close();
		return Response.noContent().build();
	}

}
